package com.party.mobile.biz.verifyCode;

import com.google.common.base.Strings;
import com.party.common.constant.Constant;
import com.party.common.redis.StringJedis;
import com.party.common.utils.EncryptUtil;
import com.party.core.model.system.SysConfig;
import com.party.core.service.system.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 验证码业务接口
 * Created by wei.li
 *
 * @date 2017/2/25 0025
 * @time 10:47
 */

@Service
public class VerifyCodeBizService {

    @Autowired
    private StringJedis stringJedis;

    @Autowired
    private ISysConfigService sysConfigService;

    private static final String SMS_CODE_SWITCH = "smsCodeSwitch";

    //盐
    private static final String salt = "tongxingzhe";

    /**
     * 验证码验证
     * @param key 验证的key值
     * @param code 待验证码
     * @return 验证结果（true/false）
     */
    public boolean verify(String key, String code){
        //验证验证码
        String verifyCode = stringJedis.getValue(key);
        if (null == verifyCode || !code.equals(verifyCode)) {
            return false;
        }
        return true;
    }

    /**
     * 是否需要验证码
     * @param phone 手机号
     * @return 是否需要（true/false）
     */
    public boolean isNeedVerify(String phone){
        //开关是否开启
        SysConfig sysConfig = sysConfigService.findByCode(SMS_CODE_SWITCH);
        if (null != sysConfig && Constant.STR_TRUE.equals(sysConfig.getValue())){
            String verifyBoxPopupNum_str = stringJedis.getValue(Constant.VERIFYBOX_POPUP_NUM + phone);

            int verifyBoxPopupNum = verifyBoxPopupNum_str==null? 0:Integer.parseInt(verifyBoxPopupNum_str);

            SysConfig sysConfig_verifyBox = sysConfigService.findByCode(Constant.VERIFYBOX_POPUP_NUM);

            if (null!=sysConfig_verifyBox&&verifyBoxPopupNum<Integer.parseInt(sysConfig_verifyBox.getValue())){

                return false;
            }
        }
        return true;
    }

    /**
     * 是否需要验证码
     * @param idCard 手机号
     * @return 是否需要（true/false）
     */
    public boolean isNeedVerifyIdCard(String idCard){
        if (null != idCard ){
            String isNeed = stringJedis.getValue(Constant.IS_NEED_IDCARD_VERIFY + idCard);
            if (Strings.isNullOrEmpty(isNeed)){
                return false;
            }
        }
        return true;
    }



    /**
     * 解密
     * @param code 验证码
     * @return 解密
     */
    public String encrypt(String code){
        String cipher = EncryptUtil.MD5Hex(code.toUpperCase() + salt);
        return cipher;
    }

}
